package com.wstuo.common.tools.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.wstuo.common.tools.dto.SMSMessageDTO;
import com.wstuo.common.tools.service.ISMSRecordService;
import com.wstuo.common.security.utils.HtmlSpirit;
import com.wstuo.common.security.utils.LanguageContent;

/**
 * 移动商务
 * @author QXY
 *
 */
public class WanCiSMSHelper implements ISMSSender{
	
	private static final Logger LOGGER = Logger.getLogger(WanCiSMSHelper.class ); 
	@Autowired
	private ISMSRecordService smsRecordService;

	private String doSend(String postUrl,String phoneNumbers, String message) {
		LanguageContent languageContent=LanguageContent.getInstance();
		HttpURLConnection httpconn = null;
		String result = "-20";
		if(phoneNumbers!=null && message!=null){//发送短信
			
			String msg=null;
			try {
				/**
				 * 短信平台规定使用的编码是:gb2312; 
				 */
				msg = URLEncoder.encode(message+languageContent.getContent("WanCiSMSHelper.doSend.encode"), "gb2312");
			} catch (UnsupportedEncodingException e) {
				LOGGER.error(e.getMessage());
			}
			postUrl=postUrl.replace("{content}",msg).replace("{to}",phoneNumbers.replace(" ", ""));
		}
		
		BufferedReader rd = null;
		try {
			URL url = new URL(postUrl);
			httpconn = (HttpURLConnection) url.openConnection();
			rd = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
			result = rd.readLine();
			
		} catch (MalformedURLException e) {
			LOGGER.error(e.getMessage());
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
			
		} finally {
			if (httpconn != null) {
				httpconn.disconnect();
				httpconn = null;
			}
			try {
				if(rd!=null){
					rd.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
		return result;
	}
	
	
	public SMSMessageDTO SendSms(String postUrl,String mobile, String content, boolean isSystem,boolean saveHistory) {
		
		SMSMessageDTO dto=new SMSMessageDTO();
		dto.setSendCount(0);
		dto.setCostMoney("");
		dto.setTotalMoney("");
		String [] mobilePath=ContentSpliter.getMobileArrFromString(mobile);
		//删除Html
		String smsContent=HtmlSpirit.delHTMLTag(content);
		String [] contentPath=ContentSpliter.getMsgArrFromString(smsContent);
		
		//循环发送
		for(int i=0;i<mobilePath.length;i++){
			
			if(!"".equals(mobilePath[i].trim())){
				for(int j=0;j<contentPath.length;j++){
					dto=switchMessage(doSend(postUrl,mobilePath[i].trim(),contentPath[j].trim()));
					if(saveHistory){//保存历史记录
						smsRecordService.saveSMSHistory(mobilePath[i].trim(),contentPath[j].trim(),isSystem);
					}
				}
			}
		}
		
		return dto;
	}
	
	/**
	 * 查询余额.
	 */
	public SMSMessageDTO queryMoney(String postUrl) {
		
		//初始化数据
		String totalMoney= doSend(postUrl,null,null);
		SMSMessageDTO dto=new SMSMessageDTO();
		dto.setTotalMoney(totalMoney+"_yuan");
		return dto;
	}

	/**
	 * 查询连接是否可用.
	 */
	public Boolean testConnection(String postUrl) {
		boolean result = false; 
		String totalMoney = doSend(postUrl,null,null);
		Double money=Double.parseDouble(totalMoney.replace("nums=",""));
		
		if(money>0){
			result = true;
		}
		return result;
	}
	
	
	/**
	 * switchMsg
	 * @param args
	 * @return SMSMessageDTO
	 */
	private static SMSMessageDTO switchMessage(String msgInput){
		
		LanguageContent languageContent=LanguageContent.getInstance();
		SMSMessageDTO dto=new SMSMessageDTO();
		if(msgInput.indexOf("/")!=-1){
			String [] arr=msgInput.split("/");
			if(arr.length>0){
				switch(Integer.parseInt(arr[0])){
				case 0:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsg"));break;
				case -1:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgz"));break;
				case -2:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgn"));break;
				case -3:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgm"));break;
				case -4:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgc"));break;
				case -5:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgs"));break;
				case -6:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgd"));break;
				case -7:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgb"));break;
				case -10:dto.setStateMsg(languageContent.getContent("WanCiSMSHelper.SMSMessageDTO.StateMsgl"));break;
				}
			}
			
			if(arr.length>1){
				dto.setSendCount(Integer.parseInt(arr[1].replace("Send:", "")));
			}
			if(arr.length>2){
				dto.setCostMoney(arr[2].replace("Consumption:", "")+"_yuan");
			}
			if(arr.length>3){
				dto.setTotalMoney(arr[3].replace("Tmoney:", "")+"_yuan");
			}
			if(arr.length>4){
				dto.setSid(arr[4].replace("sid:", ""));
			}
		}
		return dto;
	}

}
